package logic

import (
	"context"
	"fmt"
	"login/model/mysql"
	"login/pkg"

	"login/loginrpc/internal/svc"
	"login/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *loginrpc.RegisterUserRequest) (*loginrpc.RegisterUserResponse, error) {
	// todo: add your logic here and delete this line

	var users mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&users)

	if users.ID != 0 {
		return nil, fmt.Errorf("该账号已被注册,请重新输入")
	}

	captcha, _ := mysql.Rdb.Get(l.ctx, "captKey"+in.Account).Result()
	if in.Captcha != captcha {
		return nil, fmt.Errorf("图形验证码不正确,请重新输入")
	}

	smscaptcha, _ := mysql.Rdb.Get(l.ctx, "SmsKey"+in.Account).Result()
	if in.SmsCaptcha != smscaptcha {
		return nil, fmt.Errorf("短信验证码不正确,请重新输入")
	}

	data := mysql.User{
		Account:    in.Account,
		Password:   pkg.Md5str1(in.Password),
		Captcha:    in.Captcha,
		SmsCaptcha: in.SmsCaptcha,
	}
	mysql.DB.Create(&data)
	return &loginrpc.RegisterUserResponse{
		UserId: int64(data.ID),
	}, nil
}
